#include "getbackpasswordwidget.h"
#include "ui_getbackpasswordwidget.h"
#include <QDebug>

GetBackPasswordWidget::GetBackPasswordWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GetBackPasswordWidget),
    m_pUserManager(nullptr)
{
    ui->setupUi(this);

    connect(ui->resetPasswordBtn, &QPushButton::clicked, this, &GetBackPasswordWidget::onResetPasswordBtnClicked);
    connect(ui->btnBackToLogin, &QPushButton::clicked, this, [this]() {
        emit display(0); // 返回登录页面
    });
}

void GetBackPasswordWidget::setUserManager(UserManager* userManager)
{
    if (m_pUserManager) {
        m_pUserManager->deleteLater();
    }
    m_pUserManager = userManager;
}

void GetBackPasswordWidget::onResetPasswordBtnClicked()
{
    QString username = ui->usernameLineEdit->text().trimmed();
    QString input = ui->inputLineEdit->text().trimmed();
    QString newPassword = ui->newPasswordLineEdit->text();
    QString confirmPassword = ui->confirmPasswordLineEdit->text();

    // 输入验证
    if (username.isEmpty() || input.isEmpty() || newPassword.isEmpty()) {
        emit sendMessage("所有字段都必须填写");
        return;
    }

    if (newPassword != confirmPassword) {
        emit sendMessage("两次输入的密码不一致");
        return;
    }

    if (!m_pUserManager) {
        emit sendMessage("系统错误：用户管理器未初始化");
        return;
    }

    // 调用 UserManager 的密码重置方法
    auto result = m_pUserManager->resetPassword(username, input, newPassword);

    if (result.first) {
        emit sendMessage("密码重置成功");
        emit display(0); // 返回登录页面

        // 清空输入框
        ui->usernameLineEdit->clear();
        ui->inputLineEdit->clear();
        ui->newPasswordLineEdit->clear();
        ui->confirmPasswordLineEdit->clear();
    } else {
        handleResetError(result.second);
    }
}

void GetBackPasswordWidget::handleResetError(UserManager::UserError error)
{
    QString errorMsg;
    switch (error) {
        case UserManager::UserError::UserNotFound:
            errorMsg = "未找到匹配的用户信息";
            break;
        case UserManager::UserError::WeakPassword:  // 新增对弱密码错误的处理
            errorMsg = "密码强度不足，需包含大小写字母、数字和特殊字符";
            break;
        case UserManager::UserError::ConnectionError:
            errorMsg = "无法连接到服务器";
            break;
        default:
            errorMsg = "密码重置失败，请稍后再试";
            break;
    }
    emit sendMessage(errorMsg);
}

GetBackPasswordWidget::~GetBackPasswordWidget()
{
    delete ui;
}
